import { IJson } from "../../interface/type"
import utilTool from "../../util/tool"
import { swaggerConfig } from '../../swaggerConfig'

function getSchema(children: IJson, parentKey: string, arr: string[][], index: number) {
  const fArr: string[] = []
  if (parentKey) {
    fArr.unshift(`export const ${parentKey}Schemas = [`)
    parentKey = parentKey + '.'
    // fArr.push(``)
  } else {
    fArr.push(`export const formSchemas = [`)
  }
  console.log('-chidren--:', JSON.stringify(children))
  for (const key of Object.keys(children)) {
    const item = children[key]
    if (typeof item !== "object") {
      continue
    }
    // const currentKey = parentKey + key
    const currentKey = key
    if (item && Object.prototype.hasOwnProperty.call(item, 'children')) {
      getSchema(item.children, currentKey, arr, arr.length)
    } else if (item) {
      const upServerName = utilTool.firstLower(utilTool.lineToUp(swaggerConfig.serverName))
      utilTool.updateCompProp(item, key, upServerName)
      const descArr = utilTool.getDescription(item?.description)
      fArr.push(`
      {
        field: '${currentKey}',
        label: '${descArr[0]}:',${descArr[1]}
        component: '${item.component}',
        ${item.compProps}
      },`)
    }
  }
  fArr.push(`]
  `)
  arr[index] = fArr
}

// 根据请求参参数生成搜索条件配置
function getSchemas(json: IJson): string {
  if (!json?.parameters) {
    return ''
  }
  const cjson = JSON.parse(JSON.stringify(json.parameters))
  console.log('---------->cjson： ', JSON.stringify(json.parameters))
  const arr: string[][] = [[]]
  getSchema(cjson, '', arr, 0)
  const res:string[] = []
  arr.forEach((item) => {
    res.push(item.join(''))
  })
  return res.join('')
}

export function editDataTemp(json: IJson, pageConfig: IJson) {
  console.log('开始读取数据，准备生成', pageConfig.modify.fileName + '.data.js')
  const enumFileName: string = utilTool.upToLine(`co-${utilTool.firstLower(swaggerConfig.serverName)}Enum`)
  const upServerName = utilTool.lineToUp(swaggerConfig.serverName)
  const lowServerName = utilTool.firstLower(upServerName)
  return `import ${lowServerName}Enum from '@/assets/js/enum/${enumFileName}'
import util from '@/assets/js/co-util'
  ${getSchemas(json)}
  `
}

